<?php
namespace app\common\business;

use app\common\model\mysql\User as UserModel;
use app\common\lib\Str;
use app\common\lib\Time;

class User
{
    public $model = null;
    public function __construct()
    {
        $this->model = new UserModel();
    }

    public function login($data)
    {
        $redisCode = cache(config('redis.code_pre').$data['phone_number']);
        if (empty($redisCode) || $data['code'] != $redisCode) {
            throw new \think\Exception('验证码错误', -1999);
        }

        $user = $this->findUserByPhone($data['phone_number']);

        if (empty($user)) {
            $username = 'joe-'.$data['phone_number'];
            $userData = [
                'username' => $username,
                'phone_number' => $data['phone_number'],
                'type' => $data['type'],
                'status' => UserModel::STATUS_NORMAL,
                'create_time' => time(),
                'update_time' => time(),
            ];

            try {
                $this->model->save($userData);
                $userId = $this->model->id;
            } catch (\Exception $e) {
                throw new \think\Exception('数据库内部异常', -2001);
            }
        } else {
            $updateData = [
                'last_login_time' => time(),
                'last_login_ip' => request()->ip(),
            ];

            $updateResult = $this->model->updateUserById($user['id'], $updateData);
            if (!$updateResult) {
                throw new \think\Exception('更新数据失败', -2002);
            }
            $userId = $user['id'];
            $username = $user['username'];
        }

        $token = Str::getLoginToken($data['phone_number']);
        $redisData = [
            'id' => $userId,
            'username' => $username,
        ];

        $res = cache(config('redis.token_pre').$token, $redisData, Time::userLoginExpiresTime($data['type']));

        return $res ? ['token'=>$token, 'username'=>$username] : false;
    }


    public function findUserByPhone($phone)
    {
        $user = $this->model->findUserByPhone($phone);

        if (!$user || $user->status != UserModel::STATUS_NORMAL) {
            return [];
        }
        return $user->toArray();
    }

    public function getNormalUserById($id)
    {
        $user = $this->model->getUserById($id);
        if (!$user || $user->status != \app\common\model\mysql\User::STATUS_NORMAL) {
            return [];
        }
        return $user->toArray();
    }

    public function getNormalUserByUsername($username)
    {
        $user = $this->model->getUserByUsername($username);
        if (!$user || $user->status != \app\common\model\mysql\User::STATUS_NORMAL) {
            return [];
        }
        return $user->toArray();
    }

    public function update($id, $data)
    {
        $user = $this->getNormalUserById($id);
        if (!$user) {
           throw new \think\Exception('不存在用户');
        }

        $userResult = $this->getNormalUserByUsername($data['username']);
        if ($userResult && $userResult['id'] != $id) {
            throw new \think\Exception('用户名已使用');
        }
        return $this->model->updateById($id, $data);
    }

    public function updateRedis($id, $data)
    {

        if(empty($id) || empty($data) || !is_array($data)) {
            throw new \think\Exception('数据异常');
        }

        $user = $this->getNormalUserById($id);
        if (!$user) {
            throw new \think\Exception('不存在用户');
        }

        $redisData = [
            'id' => $id,
            'username' => $data['username'],
        ];

        $res = cache(config('redis.token_pre').$data['token'], $redisData);

        return $res;
    }
}